package com.dankegongyu.lib.common.util;

import android.Manifest;
import android.content.pm.PackageManager;
import androidx.fragment.app.FragmentActivity;
import androidx.core.content.ContextCompat;

import java.io.File;
import java.io.IOException;

/**
 * @author wpq
 * @version 1.0
 */
@SuppressWarnings("ResultOfMethodCallIgnored")
public class DKFileUtil {

    private DKFileUtil() {
        throw new AssertionError("cannot be instantiated");
    }

    /**
     * 请求文件读写权限
     *
     * @param activity Activity
     * @param callback {@link DKPermission.Callback}
     */
    public static void requestStoragePermissions(FragmentActivity activity, DKPermission.Callback callback) {
        DKPermission.requestStoragePermissions(activity, callback);
    }

    /**
     * 创建文件夹，文件夹路径中包含当前App包名，创建策略：
     * 1.有SD卡且有读写权限：/storage/emulated/0/包名/文件夹
     * 2.有SD卡但没有读写权限：/storage/emulated/0/Android/data/包名/files/文件夹
     * 3.没有SD卡或SD卡文件夹创建失败：/data/data/包名/files/文件夹
     *
     * @param dirName 文件夹名称
     * @return 目标文件
     */
    public static File createAppDir(String dirName) {
        String packageName = GlobalContext.getAppContext().getPackageName();
        // 1.先尝试注释中第1中情况
        if (hasStoragePermission()) {
            File dir1 = createDir(DKPathUtil.getExternalStoragePath(), packageName + File.separator + dirName);
//        DKLog.e("第1种方式创建文件夹" + (dir1.exists() ? "成功" : "失败") + "，文件夹路径：" + dir1.getAbsolutePath());
            if (dir1.exists()) {
                return dir1;
            }
        }
        // 2.如果创建失败，尝试第2种情况
        File dir2 = createDir(DKPathUtil.getExternalAppFilesPath(), dirName);
//        DKLog.e("第2种方式创建文件夹" + (dir2.exists() ? "成功" : "失败") + "，文件夹路径：" + dir2.getAbsolutePath());
        if (dir2.exists()) {
            return dir2;
        }
        // 3.如果创建失败，尝试第3中情况
        File dir3 = createDir(DKPathUtil.getInternalAppFilesPath(), dirName);
//        DKLog.e("第3种方式创建文件夹" + (dir3.exists() ? "成功" : "失败") + "，文件夹路径：" + dir3.getAbsolutePath());
        if (dir3.exists()) {
            return dir3;
        }
        return null;
    }

    private static boolean hasStoragePermission() {
        return ContextCompat.checkSelfPermission(GlobalContext.getAppContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
                && ContextCompat.checkSelfPermission(GlobalContext.getAppContext(), Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
    }

    public static File createAppFile(String fileName) {
        return createAppFile("", fileName);
    }

    /**
     * 创建文件，文件路径中包含当前App包名，创建策略：
     * 1.有SD卡且有读写权限：/storage/emulated/0/包名/文件夹/文件
     * 2.有SD卡但没有读写权限：/storage/emulated/0/Android/data/包名/files/文件夹/文件
     * 3.没有SD卡或SD卡文件夹创建失败：/data/data/包名/files/文件夹/文件
     *
     * @param dirName  文件夹名称
     * @param fileName 文件名称
     * @return 目标文件
     */
    public static File createAppFile(String dirName, String fileName) {
        String packageName = GlobalContext.getAppContext().getPackageName();
        // 1.先尝试注释中第1中情况
        if (hasStoragePermission()) {
            File dir1 = createDir(DKPathUtil.getExternalStoragePath(), packageName + File.separator + dirName);
//        DKLog.e("第1种方式创建文件夹" + (dir1.exists() ? "成功" : "失败") + "，文件夹路径：" + dir1.getAbsolutePath());
            if (dir1.exists()) {
                return dir1;
            }
        }
        // 2.如果创建失败，尝试第2种情况
        File dir2 = createDir(DKPathUtil.getExternalAppFilesPath(), dirName);
        File file2 = createNewFile(dir2, fileName);
//        DKLog.e("第2种方式创建文件" + (file2.exists() ? "成功" : "失败") + "，文件路径：" + file2.getAbsolutePath());
        if (file2.exists()) {
            return file2;
        }
        // 3.如果创建失败，尝试第3中情况
        File dir3 = createDir(DKPathUtil.getInternalAppFilesPath(), dirName);
        File file3 = createNewFile(dir3, fileName);
//        DKLog.e("第3种方式创建文件" + (file3.exists() ? "成功" : "失败") + "，文件路径：" + file3.getAbsolutePath());
        if (file3.exists()) {
            return file3;
        }
        return null;
    }

    private static File createDir(String parent, String child) {
        File dir = new File(parent, child);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return dir;
    }

    private static File createDir(File parent, String child) {
        File dir = new File(parent, child);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return dir;
    }

    private static File createNewFile(String parent, String child) {
        File file = new File(parent, child);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file;
    }

    private static File createNewFile(File parent, String child) {
        File file = new File(parent, child);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file;
    }

}
